package spring.beanLife;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertySources;
import org.springframework.core.io.ClassPathResource;

import java.util.Objects;

public class TestBeanLifeCycle {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        context.getBean("userInfoBean");
        // 关闭容器，触发 bean 的销毁方法

        // Environment 只能加载 @PropertySource 里的配置
        Environment environment = context.getBean(Environment.class);
        System.out.println(environment.getProperty("zookeeper.host"));

        PropertySources propertySources = context.getBean(PropertySourcesPlaceholderConfigurer.class).getAppliedPropertySources();
        System.out.println(Objects.requireNonNull(propertySources.get(PropertySourcesPlaceholderConfigurer.LOCAL_PROPERTIES_PROPERTY_SOURCE_NAME))
                .getProperty("me.constraints.Size.message"));
        context.close();
    }

    @Configuration
    @PropertySource("classpath:common.conf")
    public static class AppConfig {

        @Bean
        public MyInstantiationAwareBeanPostProcessor instantiationAwareBeanPostProcessor() {
            return new MyInstantiationAwareBeanPostProcessor();
        }

        @Bean(initMethod = "initMethod", destroyMethod = "destroyMethod")
        public UserInfoBean userInfoBean() {
            return new UserInfoBean();
        }

        @Bean
        public ObjectMapper objectMapper() {
            return new ObjectMapper();
        }

        @Bean
        public MyBeanPostProcessor beanPostProcessor() {
            return new MyBeanPostProcessor();
        }

        @Bean
        public MyBeanFactoryPostProcessor beanFactoryPostProcessor() {
            return new MyBeanFactoryPostProcessor();
        }

        /**
         * TODO PropertySourcesPlaceholderConfigurer 配置的值只能用 @Value 访问
         *  或者是依赖注入当前对象，然后 PropertySourcesPlaceholderConfigurer.get("localProperties").getProperty()
         */
        @Bean
        public PropertySourcesPlaceholderConfigurer sourcesPlaceholderConfigurer() {
            PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
            configurer.setLocation(new ClassPathResource("ValidationMessages.properties"));
            return configurer;
        }

    }
}
